import axios from 'axios';
import {message} from 'antd';
import Qs from 'qs';
import { toJS } from 'mobx';
const baseurl = '';

/**
 * 创建xhr实例
 * 路径前缀
 * 超时失败时间
 */
const service = axios.create ({
  //baseURL: baseurl,
  timeout: 50000,
  async: true,
  crossDomain: true,
  withCredentials: true,
  headers: {
    Accept: '*/*',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  },
  transformRequest: [
    function (data) {
      // 对 data 进行任意转换处理
      return Qs.stringify (data);
    },
  ],
});
/**
 * @desc 设置服务请求拦截器
 * 定义token请求设置
 */
service.interceptors.request.use (
  config => {
    if (sessionStorage.getItem ('authToken')) {
      config.headers['authToken'] = sessionStorage.getItem ('authToken');
    }
    return config;
  },
  error => {
    Promise.reject (error);
  }
);

/**
 * @desc 设置服务响应拦截器
 * 截取返回状态 统一定义成功失败
 */
service.interceptors.response.use (
  response => {
    const data = response.data;
    if (data.code == 12 || data.code == 10) {
      console.log('111111-------222222')
      window.location.href = "#/login";
      // window.location.href = '#/user/login';
    }

 
    if(data.success) {
      if (typeof data.data == 'object' && data.data != null && !data.data.rows) {
        data.data.rows = [];
      }

      if (Array.isArray (data.data)) {
        data.data.forEach ((vl, i) => {
          vl.key = 'key_' + parseInt (Math.random () * 10000000000) + '_' + i;
        });
      }
    }else{
      message.error (data.message);
    }
    return data
  },
  error => {
    console.log ('err' + error);
    return Promise.reject (error);
  }
);

const get = (url, params = {}) => {
  return service ({
    url,
    method: 'get',
    params,
  }).then(rs=> {
    console.info("成功数据",rs)

    return rs;
  },rj=> {
    console.info("错误数据",rj)

    return rj;
  });
};

const post = (url, data = {}) => {
  console.log ('data', data);
  return service ({
    url: url,
    method: 'post',
    data,
  }).then(rs=> {
    console.info("成功数据",rs)
    return rs;
  },rj=> {
    console.info("错误数据",rj)
    return rj;
  });
};

const postForm = (url, data = {}) => {
  let config = {
    headers: {
      authToken: sessionStorage.getItem ('authToken'),
      'Content-Type': 'application/x-www-form-urlencoded',
    },
  };

  let ret = '';
  for (let it in data) {
    if (typeof data[it] == 'object') {
      const obj = data[it];
      if(Array.isArray(toJS(obj)) && typeof obj[0] != 'object' ) {
        ret +=  encodeURIComponent (it) + "=" +
          '[' +
          toJS(obj).toString() +
          ']' + '&';
      } else {
        obj.forEach ((vl, i) => {
          for (let c in vl) {
            const child = vl[c];
            if (typeof child == 'object') {
              child.forEach ((third, thirdIndex) => {
                for (var s in third) {
                  ret +=
                    encodeURIComponent (it) +
                    '[' +
                    i +
                    '].' +
                    encodeURIComponent (c) +
                    '[' +
                    thirdIndex +
                    '].' +
                    encodeURIComponent (s) +
                    '=' +
                    encodeURIComponent (third[s]) +
                    '&';
                }
              });
            } else {
              ret +=
                encodeURIComponent (it) +
                '[' +
                i +
                '].' +
                encodeURIComponent (c) +
                '=' +
                encodeURIComponent (vl[c]) +
                '&';
            }
          }
        });
      }
    } else {
      ret +=
        encodeURIComponent (it) + '=' + encodeURIComponent (data[it]) + '&';
    }
  }

  return axios.post (baseurl + url, ret, config).then (response => {
    const data = response.data;
    console.log('data----', data)
    if (data.code == 12) {
      window.location.href = '#/user/login';
    } else if (data.code != 1 && data.code !== '200') {
      message.error (data.message);
    }
    return data;
  });
};

const postFile = (url, data = {}) => {
  let config = {
    headers: {
      authToken: sessionStorage.getItem ('authToken'),
      'Content-Type': 'multipart/form-data',
    },
  };

  return axios.post (baseurl + url, data, config).then(rs=> {
    return rs.data;
  });
};

export {get, post, service, postFile, axios, postForm};
export default service;